// 生成器替代迭代器
function* createArrayIterator(arr) {
  // 1. 第一种：迭代器
  // let index = 0;
  // return {
  //   next() {
  //     if (index < arr.length) {
  //       return { done: false, value: arr[index++] };
  //     } else {
  //       return { done: true, value: undefined };
  //     }
  //   },
  // };

  // 2. 第二种
  // for (const item of arr) {
  //   yield item;
  // }

  // 3. 第三种 yield* 可迭代对象
  yield* arr;
}

// const names = ["abc", "cba", "nba"];
// const namesIterator = createArrayIterator(names);

// console.log(namesIterator.next());
// console.log(namesIterator.next());
// console.log(namesIterator.next());
// console.log(namesIterator.next());

// 2. 创建一个函数，这个函数可以迭代一个范围内的数字
// 10 20
function* createRangeIterator(start, end) {
  // let index = start;
  // return {
  //   next() {
  //     if (index < end) {
  //       return { done: false, value: index++ };
  //     } else {
  //       return { done: true, value: undefined };
  //     }
  //   },
  // };

  let index = start;
  while (index < end) {
    yield index++;
  }
}

// const rangeIterator = createRangeIterator(10, 20);
// console.log(rangeIterator.next());
// console.log(rangeIterator.next());
// console.log(rangeIterator.next());
// console.log(rangeIterator.next());
// console.log(rangeIterator.next());
// console.log(rangeIterator.next());

// 3.
class ClassRoom {
  constructor(address, name, students) {
    this.address = address;
    this.name = name;
    this.students = students;
  }

  entry(newStudent) {
    this.students.push(newStudent);
  }

  // [Symbol.iterator] = function* () {
  //   yield* this.students;
  // };

  *[Symbol.iterator]() {
    yield* this.students;
  }
}

const classroom = new ClassRoom("8号楼102", "计算机教室", [
  "james",
  "kobe",
  "curry",
  "why",
]);

for (const item of classroom) {
  console.log(item);
}
